<template>
  <div class="spec-preview">
    <img :src="image.imgUrl" />
    <div class="event" @mousemove="handle" ref="event"></div>
    <!-- 大图 -->
    <div class="big">
      <img
        :src="image.imgUrl"
        :style="{ left: -scale * left + 'px', top: -scale * top + 'px' }"
      />
    </div>
    <div
      class="mask"
      ref="mask"
      :style="{ left: left + 'px', top: top + 'px' }"
    ></div>
  </div>
</template>

<script>
import throttle from 'lodash/throttle'
export default {
  name: 'Zoom',
  props: {
    image: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      // 遮罩层左上角的定位
      left: 0,
      top: 0,
      // 遮罩层的宽高
      smallWidth: 0,
      smallHeight: 0,
      // 最大值
      maxRight: 0,
      maxDown: 0,
      // 小图与大图的比例(大图宽/小图宽)
      scale: 0,
    }
  },
  methods: {
    handle: throttle(function (e) {
      // offsetX:鼠标距离容器左边界的距离
      // clientX:鼠标在可视区的位置
      // pageX:鼠标在整个页面上的位置
      // layerX:鼠标距离容器组件的位置
      // offsetLeft:距离最近的定位父级左侧的位置
      let mask = this.$refs.mask
      let event = this.$refs.event
      let left, top
      // 遮罩层的宽度
      this.smallWidth = mask.clientWidth
      this.smallHeight = mask.clientHeight
      // 移动的最大值
      this.maxRight = event.clientWidth - mask.clientWidth
      this.maxDown = event.clientHeight - mask.clientHeight
      // 大小图的比例
      this.scale = event.clientWidth / mask.clientWidth
      // 遮罩层左上角的定位
      left = e.offsetX - this.smallWidth / 2
      if (left < 0) left = 0
      if (left > this.maxRight) left = this.maxRight
      top = e.offsetY - this.smallHeight / 2
      if (top < 0) top = 0
      if (top > this.maxDown) top = this.maxDown

      // 响应式
      this.left = left
      this.top = top
    }, 1000 / 60),
  },
}
</script>

<style lang="less">
.spec-preview {
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid #ccc;

  img {
    width: 100%;
    height: 100%;
  }

  .event {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 998;
  }

  .mask {
    width: 50%;
    height: 50%;
    background-color: rgba(0, 255, 0, 0.3);
    position: absolute;
    left: 0;
    top: 0;
    display: none;
  }

  .big {
    width: 100%;
    height: 100%;
    position: absolute;
    top: -1px;
    left: 100%;
    border: 1px solid #aaa;
    overflow: hidden;
    z-index: 998;
    display: none;
    background: white;

    img {
      width: 200%;
      max-width: 200%;
      height: 200%;
      position: absolute;
      left: 0;
      top: 0;
    }
  }

  .event:hover ~ .mask,
  .event:hover ~ .big {
    display: block;
  }
}
</style>
